// function* gen() {
//   let a1 = yield "sleep";
//   console.log(a1);
//   let a2 = yield "eat";
//   console.log(a2);
//   let a3 = yield "coding";
//   console.log(a3);
// }
let runtime = {
  wrap(iteratorFn) {
    const _context = {
      next: 0,
      done: false,
      sent: undefined,
      stop() {
        this.done = true;
      },
    };
    return {
      next(v) {
        _context.sent = v; // 下一次的next传递的参数会交给sent
        let value = iteratorFn(_context);
        return { value, done: _context.done };
      },
    };
  },
};
// 生成器函数就是普通的一个函数，内部通过指针来控制执行函数对应的部分
function gen() {
  var a1, a2, a3;
  return runtime.wrap(function gen$(_context) {
    // it
    while (1)
      // 状态机
      switch ((_context.prev = _context.next)) {
        case 0:
          _context.next = 2;
          return "sleep";
        case 2:
          a1 = _context.sent;
          console.log(a1);
          _context.next = 6;
          return "eat";
        case 6:
          a2 = _context.sent;
          console.log(a2);
          _context.next = 10;
          return "coding";
        case 10:
          a3 = _context.sent;
          console.log(a3);
        case 12:
        case "end":
          return _context.stop();
      }
  });
}
let it = gen();

let sleep = it.next("a1");
console.log(sleep);
console.log(it.next("a2"));
console.log(it.next("a3"));
console.log(it.next("a3"));
